package com.luo.sc.oidc.authserver.handler.kapatcha;

import com.google.code.kaptcha.Constants;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Kaptcha 生成结果保存接口 - 默认Session保存实现
 *
 * @author luohq
 * @version 1.0.0
 * @date 2022-03-14 14:51
 */
public class DefaultKaptchaResultSaveServiceImpl implements KapatchResultSaveService {

    @Override
    public void saveResult(String resultText, HttpServletRequest request, HttpServletResponse response) {
        //获取session
        HttpSession session = request.getSession();
        //在session中设置验证码结果
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, resultText);
    }

    @Override
    public String getResult(HttpServletRequest request, HttpServletResponse response) {
        //获取session
        HttpSession session = request.getSession();
        //获取session中保存的验证码结果
        return (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
    }

    @Override
    public void clearResult(HttpServletRequest request, HttpServletResponse response) {
        //获取session
        HttpSession session = request.getSession();
        //移除session中保存的验证码结果
        session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
    }

    @Override
    public Boolean verifyResult(String resultText, HttpServletRequest request, HttpServletResponse response) {
        Boolean isVerified = this.verifyResult(resultText, request, response, false);
        //验证通过时，自动清除缓存的结果文本（避免后续被暴力使用）
        if (isVerified) {
            this.clearResult(request, response);
        }
        return isVerified;
    }

    @Override
    public Boolean verifyResult(String resultText, HttpServletRequest request, HttpServletResponse response, Boolean clearCacheResult) {
        String cacheResultText = this.getResult(request, response);
        //验证结果文本是否匹配
        Boolean isVerified = StringUtils.hasText(cacheResultText) && cacheResultText.equals(resultText);
        //清除缓存的结果文本（避免后续被暴力使用）
        if (Boolean.TRUE.equals(clearCacheResult)) {
            this.clearResult(request, response);
        }
        return isVerified;
    }
}
